import React, {useEffect, useState} from 'react';
import { Form, Button,Upload,Input, Modal,Row,message, Col,Select,DatePicker} from 'antd';
import { connect } from 'umi';
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from '@/utils/upload'
import UnitManageTable from './UnitManageTable';
import AllocationTable from "./AllocationTable";
import {getPerformanceRatioById,getOrgIdAndYearList} from '../service';
import {resultSum} from "@/utils/utils";
import {assessPeriodList} from '@/utils/constant';
import moment from 'moment';

const FormItem = Form.Item;
const {TextArea} = Input;
const {Option} = Select;
const formLayout = {
  labelCol: { span: 7 },
};
const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const UnitManageForm = (props) => {
  const { onSubmit, onCancel, loading,visible,currentUser,record,global = {}} = props;
  const [form] = Form.useForm();
  const {options = {}} = global;
  const {orgTree = []} = options;
  const [fileUploadUrls,setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [scaleInfo,setScaleInfo] = useState({});
  const [enterNum,setEnterNum] = useState(0);
  const [tempRecord,setTempRecord] = useState({});
  const [title,setTitle] = useState(null);
  const [cycle,setCycle] = useState(null);
  const [data,setData] = useState([]);
  const [tempList,setTempList] = useState([]);


  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1){
        urls.splice(index, 1);
        setFileUploadUrls(urls);
      }
    },
  };

  useEffect(() => {
    if(currentUser && visible){
      getPerformanceRatioById(1).then(res => {
        setScaleInfo(res);
      });
      setTitle(record ? '编辑' : '新建');
      if(record){
        let orgIds = record.orgIds.map(x => {return x.orgId}) || [];
        let performanceLevels = record.orgIds.map(x => {return x.performanceLevel}) || [];
        form.setFieldsValue({...record,orgNames:orgIds,createTime:moment(record.createTime),assessmentYear:moment(record.assessmentYear),fileUrls:record.fileUrl});
        setFileUploadUrls(record.fileUrl.split(','));
        if (record.fileUrl) {
          let fileList = record.fileUrl.split(',');
          fileList.forEach((item, index) => {
            uploadedFiles.push({
              uid: index,
              name: item.split('----')[1],
              status: 'done',
              url: item,
            })
          });
        }
        setCycle(record.assessmentCycle);
        onChangOrgList(orgIds,performanceLevels);
      }else{
        form.setFieldsValue({name:currentUser.name,code:currentUser.usercode,createTime:moment()});
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    uploadedFiles = [];
    setFileUploadUrls([]);
    setTempList([]);
    setData([]);
    onCancel();
  };

  const handleSubmit = async () => {
    if(resultSum(tempRecord) !== enterNum){
      message.error("分配数量不一致，请核实后再提交！");
      return;
    }
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({
      ...fieldsValue,
      assessmentNum:enterNum,
      performanceUnitVoArrayList:tempList,
      assessmentYear:moment(fieldsValue.assessmentYear).format('YYYY'),
      fileUrlList:fileUploadUrls,id:record && record.id
    });
    uploadedFiles = [];
    setData([]);
    setTempList([]);
    setFileUploadUrls([]);
  };

  const onCompute = (list) => {
    let t = {};
    setTempList(list);
    t.percentageA = list.filter(item => item.performanceLevel === 'A').length;
    t.percentageBPlus = list.filter(item => item.performanceLevel === 'B+').length;
    t.percentageB = list.filter(item => item.performanceLevel === 'B').length;
    t.percentageC = list.filter(item => item.performanceLevel === 'C').length;
    t.percentageD = list.filter(item => item.performanceLevel === 'D').length;
    setTempRecord(t);
  };

  const onChangOrgList = (orgIds) => {
    let year = form.getFieldValue('assessmentYear');
    if (year) {
      setEnterNum(orgIds.length);
      let tempList = [];
      getOrgIdAndYearList(orgIds, moment(year).format('YYYY')).then(res => {
        res?.map((it,index) => {
          let obj = {};
          if(it.month?.length > 0){
            obj = Object.assign(...it?.month);
          }
          if(it.quarter?.length > 0){
            obj = Object.assign(obj,...it?.quarter);
          }
          let temp = {key:it.orgId,orgId:it.orgId,orgName:it.orgName,...obj,performanceLevel: record ? record.orgIds.find(item => item.orgId === parseInt(it.orgId))?.performanceLevel : ''};
          tempList.push(temp);
        });
        setData(tempList);
      });
    } else {
      message.warning("请先选择考核年度！");
      form.setFieldsValue({orgNames: []});
    }
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="code" label="申请人工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="createTime" label="申请日期">
              <DatePicker className='widthStyle' disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="assessmentYear" label="考核年度" rules={[{required: true, message: '考核年度不能为空！'}]}>
              <DatePicker className='widthStyle' picker="year"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="assessmentCycle" label="考核周期" rules={[{required: true, message: '考核周期不能为空！'}]}>
              <Select placeholder="请选择考核周期" onChange={e => setCycle(e)}>
                {assessPeriodList?.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="performanceName" label="方案名称" rules={[{required: true, message: '方案名称不能为空！'}]}>
              <Input/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orgNames" label="考核单位" rules={[{required: true, message: '考核单位不能为空！'}]}>
              <Select mode="multiple" placeholder="请选择考核单位" allowClear onChange={onChangOrgList}>
                {orgTree?.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.title}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="reason" label="绩效说明">
              <TextArea rows={1}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="fileUrls" label="上传附件" rules={[{required: true, message: '附件不能为空'}]}>
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="list">
              <AllocationTable scaleInfo={scaleInfo} tempRecord={tempRecord}  enterNum={enterNum}/>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="performanceUnitVoArrayList">
              <UnitManageTable onCompute={onCompute} cycle={cycle} data={data}/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  };

  return (
    <Modal
      width={'70%'}
      destroyOnClose
      centered
      title={title + `绩效方案`}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
};

export default connect(({user,global}) => ({
  currentUser: user.currentUser,
  global
}))(UnitManageForm);
